﻿using ComLib.ComType;
using Common;
using LogLib;
using Newtonsoft.Json;
using System;
using System.Windows.Forms;
using Message = System.Windows.Forms.Message;

namespace BoardBroker
{
    public partial class FormBoardInteraction : Form
    {
        #region Events
        public event BoardActionFinishedEventHandler ActionFinished;
        protected void OnUSBControlActionFinished(USBControlActionFinishedEventArgs e)
        {
            if (ActionFinished != null)
            {
                ActionFinished(this, e);
            }
        }
        #endregion

        public FormBoardInteraction()
        {
            InitializeComponent();
        }

        public void RegisterEvents(BoardActionFinishedEventHandler handler)
        {
            ActionFinished += handler;
        }

        /// <summary>
        /// 当一个应用程序传递数据给另一个应用程序时发送此消息
        /// </summary>
        public const int WM_COPYDATA = 0x004A;

        protected override void WndProc(ref Message m)
        {
            switch (m.Msg)
            {
                case WM_COPYDATA:
                    OnCustomMsgReceived(m);
                    break;
                default:
                    break;
            }
            base.WndProc(ref m);
        }

        /// <summary>
        /// 接受来自其他窗口的自定义消息
        /// </summary>
        private void OnCustomMsgReceived(Message m)
        {
            COPYDATASTRUCT mystr = new COPYDATASTRUCT();
            Type mytype = mystr.GetType();
            mystr = (COPYDATASTRUCT)m.GetLParam(mytype);
            string jsonString = mystr.lpData;
            int nWParam = m.WParam.ToInt32();
            switch (nWParam)
            {
                case 1:
                    {
                        LEDControlActionResult args = JsonConvert.DeserializeObject<LEDControlActionResult>(jsonString);
                        break;
                    }                  
                case 2:
                    {
                        USB_CONTROL_ACTION_STATUS state = USB_CONTROL_ACTION_STATUS.Done;
                        USBControlActionResult args = JsonConvert.DeserializeObject<USBControlActionResult>(jsonString);
                        if(args.Code != 0)
                        {
                            state = USB_CONTROL_ACTION_STATUS.Failed;
                        }
                        OnUSBControlActionFinished(new USBControlActionFinishedEventArgs(args.Command, state, args.Message));
                        break;
                    }                            
                default:
                    break;
            }
        }

        private void FormBoardInteraction_Load(object sender, EventArgs e)
        {
            Log.WriteAsync("信息交互窗体加载完成.");
        }
    }
}
